<template>
<!-- 问答树维护 -->
  <div>
    <!-- 问答树维护 -->
    <div class="policy-main circulationInfo" >
      <div class="base-mian-cell-title mt clearfix">
        <div class="left fl">
          <i></i>
          <span class="tips">问答树维护</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <el-row style="margin-top: 15px;margin-left: 10px;">
        <el-col :span="24" class="pb15 pt5">
          <el-button
            :disabled="!this.checkeData||this.checkeData.sign!=2"
            type="danger"
            size="mini"
            style="margin-left: 10px"
            plain
            @click="addQuestion()"
            >新增问题
          </el-button>
          <el-button
            :disabled="!this.checkeData|| this.checkeData.sign==9999|| this.checkeData.sign==1 || this.checkeData.sign==2 || (this.checkeData.sign==4 && !this.checkeData.nextQuestion)"
            type="danger"
            size="mini"
            style="margin-left: 10px"
            plain
            @click="addAnswer()"
            >关联答案
          </el-button>
          <el-button
            :disabled="!this.checkeData||this.checkeData.sign==9999 ||this.checkeData.sign==1||this.checkeData.sign==2 || (this.checkeData.sign==4&&!this.checkeData.nextQuestion)"
            type="primary"
            size="mini"
            style="margin-left: 10px"
            plain
            @click="edit()"
            >修改
          </el-button>
          <el-button
            :disabled="!this.checkeData||this.checkeData.sign==9999 ||this.checkeData.sign==1||this.checkeData.sign==2"
            type="primary"
            size="mini"
            style="margin-left: 10px"
            plain
            @click="del()"
            >删除
          </el-button>
        </el-col>
      </el-row>

      <!--基本信息列表  -->
      <div class="costbox">
        <div class="colsty">
          <el-tree :data="data" :indent="25" :props="defaultProps" node-key="sign" :default-expanded-keys="[9999]" :expand-on-click-node="false" highlight-current @node-click="handleNodeClick">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{getShowLabel(data,node)}}
                <!-- 结束，显示核保结论 -->
                <span v-if="(data.sign == 4 || data.sign == 3) && data.isEnd == 1" class="tree-type" :style="setColor(data.underwriteConclusion)">{{getShowConclusion(data.underwriteConclusion)}}</span>
              </span>
            </span>
          </el-tree>
        </div>   
      </div>
    </div>

    <!-- 分类弹窗 -->
    <el-dialog
      :title="handleType == 'add'?'新增问卷':'编辑问卷'"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="60%"
      center
      class="dialog"
      >
      <el-form ref="form" :model="form" label-width="150px" :rules="rules" style="overflow: hidden">
        <el-col :span="12" class="common-box">
          <el-form-item label="问题编号：" prop="questionCode">
            <el-input :disabled="handleType == 'edit'" v-model="form.questionCode" placeholder="请输入问题编号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box">
          <el-form-item label="父问题编号：">
            <el-input disabled v-model="form.parentCode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="common-box">
          <el-form-item label="关联疾病：">
            <el-input disabled v-model="form.diseaseName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box" style="height:40px">
          <el-form-item label="适用人群：" prop="forPeople">
            <el-select v-model="form.forPeople" placeholder="请选择适用人群" clearable>
              <el-option
                v-for="item in crowdOptions"
                :key="item.paramCode"
                :label="item.paramName"
                :value="item.paramCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box">
          <el-form-item label="是否有效：" prop="isValid">
            <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="form.isValid"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box" style="height:40px">
          <el-form-item label="关联险类：" prop="insuranceCategoryCode">
            <el-select v-model="form.insuranceCategoryCode" placeholder="请选择关联险类" clearable>
              <el-option
                v-for="item in insureOptions"
                :key="item.paramCode"
                :label="item.paramName"
                :value="item.paramCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="common-box">
          <el-form-item label="是否多选：" prop="isMultipleChoices">
            <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="form.isMultipleChoices"></el-switch>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12" class="common-box">
          <el-form-item label="是否必答：" prop="isMustAnswer">
            <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="form.isMustAnswer"></el-switch>
          </el-form-item>
        </el-col> -->
        <el-col :span="12" class="common-box" v-if="checkeData.sign != 4">
          <el-form-item label="核保结论：" prop="underwriteConclusion">
            <el-select :disabled="form.isEnd!==1" v-model="form.underwriteConclusion" placeholder="请选择核保结论" clearable>
              <el-option
                v-for="item in conclusionOptions"
                :key="item.paramCode"
                :label="item.paramName"
                :value="item.paramCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        
        <el-col :span="12" class="common-box" v-if="checkeData.sign != 4">
          <el-form-item label="是否结束：" prop="isEnd">
            <el-switch class="tableScopeSwitch" inactive-color="#c0c0c0" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" v-model="form.isEnd" @change="endFlagChange"></el-switch>
          </el-form-item>
        </el-col>

        <el-col :span="24" class="common-box">
          <el-form-item label="问题内容：" prop="content">
            <el-input :disabled="form.isEnd==1" type="textarea" :rows="3" v-model="form.content" placeholder="请输入内容"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="common-box">
          <el-form-item label="备注：">
            <el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="config">保 存</el-button>
        <el-button @click="reset">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getQaTreeApi, getParamPageListApi, insertOrUpdateQuestionApi,removeQuestionApi,removeAnswerApi} from "@/api/setting/maintain/askMaintenance"; //调接口
export default {
  data() {
    return {
      data: [{
        categoryName: '问答树',
        sign: 9999,
        children: []
      }],
      defaultProps: {
        children: 'children',
      },

      checkeData: null,  //选中的节点数据
      handleType: 'add',  //操作类型：新增/编辑
      conclusionOptions:[],//核保结论

      // 问卷
      dialogVisible: false,
      form: {
        questionCode: '',
        parentCode: '',
        diseaseName: '',
        diseaseCode: '',
        forPeople: '',
        insuranceCategoryCode:'',
        isMultipleChoices: 0,
        isMustAnswer: 1,
        content: '',
        remark: '',
        isValid: 1,
        isEnd: 0,
        underwriteConclusion:''
      },
      crowdOptions:[],//适用人群
      insureOptions:[],//关联险类
      rules: {
        questionCode: [
          { required: true, message: '请输入问题编号', trigger: 'blur' },
        ],
        forPeople: [
          { required: true, message: '请选择适用人群', trigger: 'change' }
        ],
        insuranceCategoryCode: [
          { required: true, message: '请选择关联险类', trigger: 'change' }
        ],
        isValid: [
          { required: true, message: '请选择是否有效', trigger: 'change' }
        ],
        isMultipleChoices: [
          { required: true, message: '请选择是否多选', trigger: 'change' }
        ],
        /* isMustAnswer: [
          { required: true, message: '请选择是否必答', trigger: 'change' }
        ], */
        isEnd: [
          { required: true, message: '请选择是否结束', trigger: 'change' }
        ],
        underwriteConclusion:[
          {
            validator: (rule, value, callback) => {
              if(this.form.isEnd == 1 && !value){
                callback(new Error('请选择核保结论'))
              }else{
                callback()
              }
            }
          }
        ],
        content: [
          {
            validator: (rule, value, callback) => {
              if(this.form.isEnd == 0 && !value){
                callback(new Error('请输入问题内容'))
              }else{
                callback()
              }
            }
          }
        ],
      },
    }
  },
  activated(){
    this.$store.dispatch("loading/CHANGE_LOADING", true);
    if(this.insureOptions.length){
      this.getTree()
    }else{
      this.getInsureOptions()
    }
  },
  mounted(){
    this.getCrowdOptionsORConclusionOptions('forPeople')
    this.getCrowdOptionsORConclusionOptions('underwriteConclusion')
  }, 
  methods: {
    // 树形显示的内容
    getShowLabel(data){
      if(data.sign === 2) return data.diseaseName
      else if(data.sign === 1 || data.sign === 9999) return data.categoryName
      else if(data.sign === 3 ) {
        let categoryName = ''
        if(this.insureOptions.length){
          this.insureOptions.forEach(item=>{
            if(item.paramCode == data.insuranceCategoryCode) categoryName = item.paramName
          })
        }
        return data.content ? `${categoryName}：“${data.content}”` : `${categoryName}：`
      }else if(data.sign == 4){
        let showContent = ''
        if(data.nextQuestion){
          showContent = `“${data.contentText}：${data.nextQuestion.content}”`
        }else{
          showContent = `“${data.contentText}”`
        }
        return showContent
      }
      else return ''
    },
    // 匹配核保结论
    getShowConclusion(data){
      let conclusion = ''
      this.conclusionOptions.forEach(item=>{
        if(item.paramCode == data) conclusion = item.paramName
      })
      return conclusion
    },
    // 设置核保结论颜色样式
    setColor(data){
      let style = {background: '#68a3fc'}
      if(data == '1') style.background = '#70b603' //标体通过
      if(data == '4') style.background = '#bfbf52'  //延期
      if(data == '5') style.background = '#f76767'  //拒保
      return style
    },
    // 点击节点时触发
    handleNodeClick(data,node,el) {
      this.checkeData = data
    },
    // 设置节点的边框线
    setTreeBorder(){
      document.querySelectorAll('.create-divel').forEach(item=>{
        item.remove();
      })
      document.querySelectorAll('.el-tree-node__content').forEach(item=>{
        let divEl = document.createElement('div')
        divEl.classList.add("create-divel");
        divEl.style.position = 'absolute'
        divEl.style.height = '100%'
        divEl.style.top = '0'
        divEl.style.borderLeft = '1px dashed #ccc'
        divEl.style.left = parseInt(item.style.paddingLeft) + 12 +'px'
        if(item.nextSibling.nodeType==1) {
          item.nextSibling.appendChild(divEl)
          item.nextSibling.style.position = 'relative'
        }
      })
    },
    // 答案弹窗是否结束switch状态改变时触发
    endFlagChange(val){
      if(val==1){
        this.form.content = ''
        this.$refs['form'].clearValidate(['content']);
      }
      else{
        this.form.underwriteConclusion = ''
        this.$refs['form'].clearValidate(['underwriteConclusion']);
      }
    },
    // 点击新增问题按钮
    addQuestion(){
      this.form = {
        questionCode: '',
        parentCode: '',
        diseaseName: this.checkeData.diseaseName,
        diseaseCode: this.checkeData.diseaseCode,
        forPeople: '',
        insuranceCategoryCode:'',
        isMultipleChoices: 0,
        isMustAnswer: 1,
        content: '',
        remark: '',
        isValid: 1,
        isEnd: 0,
        underwriteConclusion:''
      }
      this.handleType = 'add'
      this.dialogVisible = true
    },
    // 点击关联答案按钮
    addAnswer(){
      if(!this.checkeData|| this.checkeData.sign==9999 || this.checkeData.sign==1 || this.checkeData.sign==2 || (this.checkeData.sign==4 && !this.checkeData.nextQuestion)) {
        this.$message.error('请在问题下关联答案！')
        return
      }
      if(this.checkeData.sign==3 && this.checkeData.isEnd == 1){
        this.$message.closeAll()
        this.$message.warning('已结束的问题不能关联答案！')
        return
      }
      if(this.checkeData.sign == 3){
        this.$router.push({
			  	path: `/home/setting/relationAnswer?id=${this.checkeData.id}&diseaseCode=${this.checkeData.diseaseCode}`
			  });
      }
      if(this.checkeData.sign == 4){
        this.$router.push({
			  	path: `/home/setting/relationAnswer?id=${this.checkeData.nextQuestion.id}&diseaseCode=${this.checkeData.nextQuestion.diseaseCode}`
			  });
      }
    },
    reset(){
      this.dialogVisible = false
    },
    // 点击新增问卷弹窗确认按钮时触发
    config(){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          insertOrUpdateQuestionApi(this.form).then((res) => {
            if (res.resultCode === 0) {
              this.$message.success('保存成功')
              this.getTree()
              this.reset()
            }else {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            }
          }).catch(err=>{
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          })
        } else {
          return false;
        }
      });
    },

    edit(){  //编辑
      this.handleType = 'edit'
      if(this.checkeData.sign == 3){//问题
        this.form = JSON.parse(JSON.stringify(this.checkeData))
        this.dialogVisible = true
      }if(this.checkeData.sign == 4){//问题
        this.form = JSON.parse(JSON.stringify(this.checkeData.nextQuestion))
        this.form.isEnd = 0
        this.dialogVisible = true
      }
      /* if(this.checkeData.sign == 3){  
        this.illnessForm = JSON.parse(JSON.stringify(this.checkeData))
        this.illnessVisible = true
      } */
      
    },
    // 删除
    del(){
      console.log(this.checkeData,'删除');
      // sign: 3 问题；4 答案
      if(this.checkeData.sign == 3){
        this.$confirm('是否删除此问题?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          removeQuestionApi({id:this.checkeData.id,questionCode:this.checkeData.questionCode}).then((res) => {
            if (res.resultCode === 0) {
              // 每次手动关闭所有弹框
              this.$message.closeAll()
              this.$message.success('删除成功')
              this.getTree()
            }else this.$store.dispatch("loading/CHANGE_LOADING", false);
          }).catch((err) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          });
        })
      }else if(this.checkeData.sign == 4){
        this.$confirm('是否删除此答案?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          removeAnswerApi({id:this.checkeData.id,answerCode:this.checkeData.answerCode}).then((res) => {
            if (res.resultCode === 0) {
              // 每次手动关闭所有弹框
              this.$message.closeAll()
              this.$message.success('删除成功')
              this.getTree()
            }else this.$store.dispatch("loading/CHANGE_LOADING", false);
          }).catch((err) => {
            this.$store.dispatch("loading/CHANGE_LOADING", false);
          });
        })
      }
    },
    // 获取适用人群数据
    getCrowdOptionsORConclusionOptions(paramGroupCode){
      let params = {
        pageNum: 1, //当前页
        pageSize: 999, //每页数
        paramGroupCode,
        isValid: 1
      }
      getParamPageListApi(params).then((res) => {
        if (res.resultCode === 0) {
          let {list} = res.data
          if(paramGroupCode == 'forPeople') this.crowdOptions = list || []
          else this.conclusionOptions = list || []
        }
      })
    },
    // 获取险类数据
    getInsureOptions(){
      let params = {
        pageNum: 1, //当前页
        pageSize: 999, //每页数
        paramGroupCode: 'category',
        isValid: 1
      }
      getParamPageListApi(params).then((res) => {
        this.getTree()
        if (res.resultCode === 0) {
          let {list} = res.data
          this.insureOptions = list || []
        }
      }).catch((err) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
      });
    },
    // 获取问答树数据
    getTree(){
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      getQaTreeApi({}).then((res) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
        if (res.resultCode === 0) {
          this.checkeData = null
          this.data = [{categoryName: '问答树',sign: 9999,children: []}]
          if(res.data && res.data.length) this.data[0].children = res.data
        }
        this.$nextTick(()=>{
          this.setTreeBorder()
        })
      }).catch((err) => {
        this.$store.dispatch("loading/CHANGE_LOADING", false);
      });
    },
   
  },
};
</script>

<style lang = "less" scoped>
.policy-main {
  background: #fff;
  .base-mian-cell-title {
    margin: 0px 20px;
    padding: 0 20px;
    height: 48px;
    line-height: 48px;
    border-bottom: 1px solid #e1e1e1;
    overflow: hidden;
    .left {
      .line {
        color: #f76767;
        float: left;
      }
      .tips {
        margin-left: 10px;
        font-weight: bold;
        float: left;
      }
      i{
        width: 2px;
        height: 16px;
        float: left;
        background: red;
        margin-top: 17px;
      }
      .input{
        display: inline-block;
        border:1px solid #e1e1e1;
        line-height: 36px;
        background-color: #fff;
        margin: 0 20px;
        width: 200px;
        padding-left: 15px;
      }
      .el-input {
        /* width: 50%; */
        margin-left: 20px;
        .el-input__inner {
          height: 34px;
          width: 180%;
        }
      }
    }
    .right {
      padding: 0 10px;
      cursor: pointer;
      .el-icon-arrow-down {
        color: #999;
        font-size: 24px;
        line-height: 48px;
      }
      .transform {
        transform: rotate(270deg);
      }
    }
  }

  .base-mian-cell-title:nth-last-of-type(1){
    background-color: #fff;
    border: 1px solid #f4f4f4;
    /* .tips{
      color: #606266;
      font-weight: normal;
    } */
  }
  .mt{
    margin-top: 0px;
  }

}

/deep/.el-table thead tr:nth-of-type(2){
  display: none;
}

.costbox{
    margin: 10px 30px 0 30px;
    padding-bottom: 15px;
    .colsty{
      border: 1px solid #ccc;
      border-radius: 5px;
      /* min-height: 43vh;
      overflow: hidden;*/
      min-height: 43vh;
       height: calc(100vh - 335px);
       overflow: auto;
    }
  }

  .tree-type{
    display: inline-block;
    padding: 0 3px;
    height: 18px;
    color: #fff;
    font-size: 12px;
    line-height: 18px;
    text-align: center;
    border-radius: 2px;
    margin-left: 10px;
  }

  /deep/ .col-reset .el-form-item__label{
    width: 85px !important;
    text-align: left !important;
  }
  /deep/ .col-reset .el-form-item__content{
    margin-left: 82px !important;
  }


/deep/ .tableScopeSwitch .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
}
/*打开时文字位置设置*/
/deep/ .tableScopeSwitch .el-switch__label--right {
    z-index: 1;
    right: -10px;
}
/*关闭时文字位置设置*/
/deep/ .tableScopeSwitch .el-switch__label--left {
    z-index: 1;
    left: 20px;
}
/*显示文字*/
/deep/ .tableScopeSwitch .el-switch__label.is-active {
    display: block;
}
/deep/ .tableScopeSwitch.el-switch .el-switch__core,
/deep/ .el-switch .el-switch__label {
    width: 50px !important;    /*开关按钮的宽度大小*/
}

/deep/ .dialog .el-dialog{
  min-width: 570px;
}

/deep/ .el-tree{
  background: #fff !important;
}

/deep/ .el-tree .el-tree-node__expand-icon.expanded {
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
}
/deep/ .el-tree .el-icon-caret-right:before {
  content: "+";
  width: 10px;
  height: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #ccc;
}
/deep/ .el-tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before{
  content: "-";
  width: 10px;
  height: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #ccc;
}
/deep/ .el-tree .is-leaf:before{
  border: none;
}
</style>